package ore.example.pokemonPb.item;

import ore.example.pokemonPb.utils.RewardData;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.jetbrains.annotations.NotNull;
import xyz.xenondevs.invui.item.ItemProvider;
import xyz.xenondevs.invui.item.builder.ItemBuilder;
import xyz.xenondevs.invui.item.impl.AbstractItem;

import static ore.example.pokemonPb.GUI.PokedexGUI.openPokedex;

public class CountItem extends AbstractItem {

    private final Player player;
    private final String cmd;
    private final String msg;
    private final String soundName;
    private final int ownedCount;
    private final int totalCount;
    private final double progress;
    private final int generation;

    public CountItem(Player player, String cmd, String msg, String soundName,
                     int ownedCount, int totalCount, int generation) {
        this.player = player;
        this.cmd = cmd;
        this.msg = msg;
        this.soundName = soundName;
        this.ownedCount = ownedCount;
        this.totalCount = totalCount;
        this.generation = generation;
        this.progress = totalCount > 0 ? (double) ownedCount / totalCount : 0.0;
    }

    @Override
    public ItemProvider getItemProvider() {
        ItemBuilder builder = new ItemBuilder(Material.BOOK)
                .setDisplayName("§6图鉴进度 - 第" + generation + "世代");

        String progressBar = createProgressBar(progress, 20);
        int percentage = (int) (progress * 100);

        builder.addLoreLines(
                "§7当前进度: §e" + ownedCount + "§7/§e" + totalCount + " §7(§b" + percentage + "%§7)",
                "",
                "§8[" + progressBar + "§8]",
                ""
        );

        boolean allCollected = ownedCount == totalCount;
        boolean hasClaimed = RewardData.hasClaimed(player.getUniqueId(), generation);

        if (allCollected && !hasClaimed) {
            builder.addLoreLines(
                    "§a✓ 恭喜！你已收集完所有宝可梦！",
                    "§b点击领取世代完成奖励"
            );
        } else if (hasClaimed) {
            builder.addLoreLines("§6★ 奖励已领取");
        } else {
            int remaining = totalCount - ownedCount;
            builder.addLoreLines(
                    "§7还需收集: §e" + remaining + "§7 只宝可梦",
                    "§7继续努力完成图鉴吧！"
            );
        }

        return builder;
    }

    private String createProgressBar(double progress, int length) {
        int filledLength = (int) (progress * length);
        int emptyLength = length - filledLength;

        StringBuilder bar = new StringBuilder("§a");
        for (int i = 0; i < filledLength; i++) bar.append("■");
        bar.append("§7");
        for (int i = 0; i < emptyLength; i++) bar.append("■");
        return bar.toString();
    }

    @Override
    public void handleClick(@NotNull ClickType clickType, @NotNull Player player, @NotNull InventoryClickEvent event) {
        boolean allCollected = ownedCount == totalCount;
        boolean hasClaimed = RewardData.hasClaimed(player.getUniqueId(), generation);

        if (hasClaimed) {
            player.sendMessage("§e你已经领取过第" + generation + "世代的图鉴奖励了！");
            return;
        }

        if (!allCollected) {
            player.sendMessage("§c你还没有集齐所有宝可梦！当前进度: " + ownedCount + "/" + totalCount);
            return;
        }

        // ✅ 发放奖励
        Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd.replace("%player%", player.getName()));
        player.sendMessage(msg.replace("%player%", player.getName()).replace("%gen%", String.valueOf(generation)));

        try {
            Sound s = Sound.valueOf(soundName);
            player.playSound(player.getLocation(), s, 1f, 1f);
        } catch (Exception ignored) {}

        // ✅ 标记为已领取
        RewardData.setClaimed(player.getUniqueId(), generation);

        // ✅ 从插件配置中读取广播模板
        FileConfiguration cfg = Bukkit.getPluginManager().getPlugin("PokemonPb").getConfig();
        String broadcast = cfg.getString("rewards.broadcast",
                "§6[宝可梦图鉴] §e玩家 §b%player% §e完成了第 §a%gen% §e世代宝可梦图鉴！快来祝贺他！");

        // ✅ 全服播报
        Bukkit.broadcastMessage(
                broadcast.replace("%player%", player.getName()).replace("%gen%", String.valueOf(generation))
        );

        // ✅ 重新打开图鉴界面刷新状态
        openPokedex(player, generation);
    }
}
